package cn.com.weshare.jiekuan.smsverifygetter;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private SmsVerifyCatcher smsVerifyCatcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        final String url = "http://10.3.0.194:5000/monkey/get_sms_info?sms_type=3";
        String url = "http://10.1.1.243:8830/monkey/add_sms_info";

        //init views
        final EditText etCode = (EditText) findViewById(R.id.et_code);
        url = etCode.getText().toString();
        final Button btnVerify = (Button) findViewById(R.id.btn_verify);

        //init SmsVerifyCatcher
        final String finalUrl = url;
        smsVerifyCatcher = new SmsVerifyCatcher(this, new OnSmsCatchListener<String>() {
            @Override
            public void onSmsCatch(String message) { // 这里的message是手机号和短信正文内容的拼接格式

//                String code = parseCode(message); // Parse verification code
//                etCode.setText(code);             // set code in edit text

                String[] content = message.split("x0x0x0y1y1y1"); // 用数组保存短信内容

                // 上传发信人手机号和短信内容到服务器
                RequestParams params = new RequestParams(finalUrl);
//                params.setAsJsonContent(true);
                params.addBodyParameter("sms_number", content[0]);
                params.addBodyParameter("sms_content", content[1]);
                params.addBodyParameter("sms_time", String.valueOf(System.currentTimeMillis() / 1000));

                x.http().post(params, new Callback.CacheCallback<String>() {
                    @Override
                    public boolean onCache(String result) {
                        return false;
                    }

                    @Override
                    public void onSuccess(String result) {
                        Log.i("tag000", "onSuccess：" + result);
                        Toast.makeText(MainActivity.this, "即时短信获取并上传成功", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Log.i("tag000", "onError：" + "Oops访问接口时出错了:" + ex.getMessage());
                        Toast.makeText(MainActivity.this, "Oops访问接口时出错了", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {
                    }
                });
            }
        });

        //set phone number filter if needed
//        smsVerifyCatcher.setPhoneNumberFilter("18301609560");
        //smsVerifyCatcher.setFilter("regexp");

        btnVerify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //send verification code to server
            }
        });
    }

    /**
     * Parse verification code
     *
     * @param message sms message
     * @return only four numbers from massage string
     */
    private String parseCode(String message) {
        Pattern p = Pattern.compile("\\b\\d{4}\\b");
        Matcher m = p.matcher(message);
        String code = "";
        while (m.find()) {
            code = m.group(0);
        }
        return code;
    }


    @Override
    protected void onStart() {
        super.onStart();
        smsVerifyCatcher.onStart();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        smsVerifyCatcher.onStop();
    }

    /**
     * need for Android 6 real time permissions
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        smsVerifyCatcher.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
